extern crate alloc;

use core::str;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

pub use ttf_parser::Language;
use tumo::base::font::{Stretch, Style, Weight};
use tumo::base::rustybuzz::ttf_parser;

type ID = usize;

#[derive(Debug, Default)]
pub struct FontDB {
	faces: Vec<FaceInfo>,
}

impl FontDB {
	pub fn load_source(&mut self, source: Source) {
		source.with_data(|data| {
			let n = ttf_parser::fonts_in_collection(data).unwrap_or(1);
			for index in 0..n {
				if let Some(info) = parse_face_info(source.clone(), data, index) {
					self.faces.push(info);
				}
			}
		});
	}
	pub fn load_file_data(&mut self, file: impl AsRef<Path>, data: &[u8]) {
		let file = file.as_ref();
		if self.faces.iter().any(|v| match &v.source {
			Source::Binary(_) => false,
			Source::File(path_buf) => path_buf == file,
			Source::SharedFile(path_buf, _) => path_buf == file,
		}) {
			return;
		}
		let n = ttf_parser::fonts_in_collection(data).unwrap_or(1);
		for index in 0..n {
			if let Some(info) = parse_face_info(Source::File(file.to_path_buf()), data, index) {
				self.faces.push(info);
			}
		}
	}
	pub fn load_data(&mut self, data: Vec<u8>) {
		self.load_source(Source::Binary(alloc::sync::Arc::new(data)));
	}
	pub fn load_file(&mut self, file: impl AsRef<Path>) {
		self.load_source(Source::File(file.as_ref().to_path_buf()));
	}
	pub fn load_mmap(&mut self, file: impl AsRef<Path>, data: memmap2::Mmap) {
		self.load_source(Source::SharedFile(file.as_ref().to_path_buf(), alloc::sync::Arc::new(data)))
	}
	pub fn load_dir<P: AsRef<Path>>(&mut self, dir: P) {
		self.load_dir_impl(dir.as_ref(), &mut Default::default(), false)
	}
	pub fn load_dir_recursive<P: AsRef<Path>>(&mut self, dir: P) {
		self.load_dir_impl(dir.as_ref(), &mut Default::default(), true)
	}

	pub fn faces(&'_ self) -> std::slice::Iter<'_, FaceInfo> {
		self.faces.iter()
	}
	pub fn face(&self, id: ID) -> Option<&FaceInfo> {
		self.faces.get(id)
	}
	pub fn with_face_data<P, T>(&self, id: ID, p: P) -> Option<T>
	where
		P: FnOnce(&[u8], u32) -> T,
	{
		let info = self.face(id)?;
		info.source.with_data(|data| p(data, info.index))
	}
}
impl FontDB {
	pub fn load_system(&mut self, recursive: bool) {
		#[cfg(target_os = "windows")]
		{
			let mut seen = Default::default();
			if let Some(ref system_root) = std::env::var_os("SYSTEMROOT") {
				let system_root_path = Path::new(system_root);
				self.load_dir_impl(&system_root_path.join("Fonts"), &mut seen, recursive);
			} else {
				self.load_dir_impl("C:\\Windows\\Fonts\\".as_ref(), &mut seen, recursive);
			}
			if let Ok(ref home) = std::env::var("USERPROFILE") {
				let home_path = Path::new(home);
				self.load_dir_impl(&home_path.join("AppData\\Local\\Microsoft\\Windows\\Fonts"), &mut seen, recursive);
				self.load_dir_impl(&home_path.join("AppData\\Roaming\\Microsoft\\Windows\\Fonts"), &mut seen, recursive);
			}
		}
		#[cfg(target_os = "macos")]
		{
			let mut seen = Default::default();
			self.load_dir_impl("/Library/Fonts".as_ref(), &mut seen, recursive);
			self.load_dir_impl("/System/Library/Fonts".as_ref(), &mut seen, recursive);
			if let Ok(ref home) = std::env::var("HOME") {
				let home_path = Path::new(home);
				self.load_dir_impl(&home_path.join("Library/Fonts"), &mut seen, recursive);
			}
		}
		#[cfg(target_os = "ios")]
		{
			let mut seen = Default::default();
			self.load_dir_impl("/Library/Fonts".as_ref(), &mut seen, recursive);
			self.load_dir_impl("/System/Library/Fonts".as_ref(), &mut seen, recursive);
			self.load_dir_impl("/System/Library/Fonts/Cache".as_ref(), &mut seen, recursive);
		}
		#[cfg(target_os = "linux")]
		{
			let mut seen = Default::default();
			self.load_dir_impl("/usr/share/fonts".as_ref(), &mut seen, recursive);
			if let Ok(ref home) = std::env::var("HOME") {
				let home_path = Path::new(home);
				self.load_dir_impl(&home_path.join(".fonts"), &mut seen, recursive);
				self.load_dir_impl(&home_path.join(".local/share/fonts"), &mut seen, recursive);
			}
		}
		#[cfg(target_os = "android")]
		{
			let mut seen = Default::default();
			if let Some(ref system_root) = std::env::var_os("ANDROID_ROOT") {
				let system_root_path = Path::new(system_root);
				self.load_dir_impl(&system_root_path.join("fonts"), &mut seen, recursive);
			} else {
				self.load_dir_impl("/system/fonts".as_ref(), &mut seen, recursive);
			}
		}
		#[cfg(target_arch = "wasm32")]
		{
			if recursive {}
		}
		// Web non
	}
}
impl FontDB {
	fn canonicalize(&self, path: PathBuf, entry: fs::DirEntry, seen: &mut HashSet<PathBuf>) -> Option<(PathBuf, fs::FileType)> {
		let file_type = entry.file_type().ok()?;
		if !file_type.is_symlink() {
			if !seen.is_empty() {
				if seen.contains(&path) {
					return None;
				}
				seen.insert(path.clone());
			}

			return Some((path, file_type));
		}

		if seen.is_empty() && file_type.is_dir() {
			seen.reserve(8192 / std::mem::size_of::<PathBuf>());

			for info in self.faces.iter() {
				let path = match &info.source {
					Source::Binary(_) => continue,
					Source::File(path) => path.to_path_buf(),
					Source::SharedFile(path, _) => path.to_path_buf(),
				};
				seen.insert(path);
			}
		}

		let stat = fs::metadata(&path).ok()?;
		if stat.is_symlink() {
			return None;
		}

		let canon = fs::canonicalize(path).ok()?;
		if seen.contains(&canon) {
			return None;
		}
		seen.insert(canon.clone());
		Some((canon, stat.file_type()))
	}
	fn load_dir_impl(&mut self, dir: &Path, seen: &mut HashSet<PathBuf>, recursive: bool) {
		let Ok(fonts_dir) = fs::read_dir(dir) else { return };
		for entry in fonts_dir.flatten() {
			let Some((path, file_type)) = self.canonicalize(entry.path(), entry, seen) else {
				continue;
			};
			if file_type.is_file() {
				match path.extension().and_then(|e| e.to_str()) {
					Some("ttf") | Some("ttc") | Some("TTF") | Some("TTC") | Some("otf") | Some("otc") | Some("OTF") | Some("OTC") => {
						self.load_file(&path);
					}
					_ => {}
				}
			} else if file_type.is_dir() {
				if recursive {
					self.load_dir_impl(&path, seen, recursive);
				}
			}
		}
	}
}

/// A single font face info.
///
/// A font can have multiple faces.
///
/// A single item of the `Database`.
#[derive(Clone, Debug)]
pub struct FaceInfo {
	/// A font source.
	///
	/// Note that multiple `FaceInfo` objects can reference the same data in case of
	/// font collections, which means that they'll use the same Source.
	pub source: Source,
	/// A face index in the `source`.
	pub index: u32,
	/// A list of family names.
	///
	/// Contains pairs of Name + Language. Where the first family is always English US,
	/// unless it's missing from the font.
	///
	/// Corresponds to a *Typographic Family* (ID 16) or a *Font Family* (ID 1) [name ID]
	/// in a TrueType font.
	///
	/// This is not an *Extended Typographic Family* or a *Full Name*.
	/// Meaning it will contain _Arial_ and not _Arial Bold_.
	///
	/// [name ID]: https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids
	pub families: Vec<(String, Language)>,
	/// A PostScript name.
	///
	/// Corresponds to a *PostScript name* (6) [name ID] in a TrueType font.
	///
	/// [name ID]: https://docs.microsoft.com/en-us/typography/opentype/spec/name#name-ids
	pub post_script_name: String,
	pub unique_id: String,
	pub full_name: String,
	/// A font face style.
	pub style: Style,
	/// A font face weight.
	pub weight: Weight,
	/// A font face stretch.
	pub stretch: Stretch,
	/// Indicates that the font face is monospaced.
	pub monospaced: bool,
	/// Design languages
	pub dlng: String,
	/// Supported languages
	pub slng: String,
}

/// A font source.
///
/// Either a raw binary data or a file path.
///
/// Stores the whole font and not just a single face.
#[derive(Clone)]
pub enum Source {
	/// A font's raw data, typically backed by a Vec<u8>.
	Binary(alloc::sync::Arc<dyn AsRef<[u8]> + Sync + Send>),
	/// A font's path.
	File(PathBuf),
	/// A font's raw data originating from a shared file mapping.
	SharedFile(PathBuf, std::sync::Arc<dyn AsRef<[u8]> + Sync + Send>),
}
impl core::fmt::Debug for Source {
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
		match self {
			Self::Binary(_) => f.debug_tuple("SharedBinary").finish(),
			Self::File(v) => f.debug_tuple("File").field(v).finish(),
			Self::SharedFile(v, _) => f.debug_tuple("SharedFile").field(v).finish(),
		}
	}
}
impl Source {
	fn with_data<T, P: FnOnce(&[u8]) -> T>(&self, p: P) -> Option<T> {
		match &self {
			Source::File(ref path) => Some(p(unsafe { &memmap2::MmapOptions::new().map(&fs::File::open(path).ok()?).ok()? })),
			Source::Binary(ref data) => Some(p(data.as_ref().as_ref())),
			Source::SharedFile(_, ref data) => Some(p(data.as_ref().as_ref())),
		}
	}
}

fn parse_face_info(source: Source, data: &[u8], index: u32) -> Option<FaceInfo> {
	let raw_face = ttf_parser::RawFace::parse(data, index).ok()?;
	let (families, post_script_name, unique_id, full_name) = parse_names(&raw_face)?;
	let (dlng, slng) = parse_meta(&raw_face).unwrap_or_default();
	let (mut style, weight, stretch) = parse_os2(&raw_face);
	let (monospaced, italic) = parse_post(&raw_face);
	if style == Style::Normal && italic {
		style = Style::Italic;
	}
	Some(FaceInfo {
		source,
		index,
		families,
		post_script_name,
		unique_id,
		full_name,
		style,
		weight,
		stretch,
		monospaced,
		slng,
		dlng,
	})
}

fn parse_meta<'a>(raw_face: &'a ttf_parser::RawFace<'a>) -> Option<(String, String)> {
	const META_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"meta");
	const DLNG_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"dlng");
	const SLNG_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"slng");
	let meta_data = raw_face.table(META_TAG)?;

	let mut s = Stream::new(meta_data);
	let _version = s.read::<u32>()?;
	let _flags = s.read::<u32>()?;
	let _reserved = s.read::<u32>()?;
	let count = s.read::<u32>()?;

	let metas = s.read_array16::<MetaRecord>(count as _)?;

	let mut dlng: Option<String> = None;
	let mut slng: Option<String> = None;
	for meta in metas {
		let start = meta.offset.0 as usize;
		let len = meta.len as usize;
		if meta.tag == DLNG_TAG {
			let value = meta_data.get(start..(start + len))?;
			let value = str::from_utf8(value).ok()?;
			dlng = Some(value.to_string());
			continue;
		}
		if meta.tag == SLNG_TAG {
			let value = meta_data.get(start..(start + len))?;
			let value = str::from_utf8(value).ok()?;
			slng = Some(value.to_string());
			continue;
		}
	}

	Some((dlng.unwrap_or_default(), slng.unwrap_or_default()))
}

struct MetaRecord {
	tag: ttf_parser::Tag,
	offset: Offset32,
	len: u32,
}
impl FromData for MetaRecord {
	const SIZE: usize = 12;
	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		let mut s = Stream::new(data);
		Self {
			tag: s.read::<ttf_parser::Tag>()?,
			offset: s.read::<Offset32>()?,
			len: s.read::<u32>()?,
		}
		.into()
	}
}
use ttf_parser::{FromData, LazyArray16};

/// A type-safe u32 offset.
#[derive(Clone, Copy, Debug)]
pub struct Offset32(pub u32);
impl FromData for Offset32 {
	const SIZE: usize = 4;

	#[inline]
	fn parse(data: &[u8]) -> Option<Self> {
		u32::parse(data).map(Offset32)
	}
}
/// A streaming binary parser.
#[derive(Clone, Default, Debug)]
pub struct Stream<'a> {
	data: &'a [u8],
	offset: usize,
}
impl<'a> Stream<'a> {
	#[inline]
	pub fn new(data: &'a [u8]) -> Self {
		Stream { data, offset: 0 }
	}

	/// Creates a new `Stream` parser at offset.
	///
	/// Returns `None` when `offset` is out of bounds.
	#[inline]
	pub fn new_at(data: &'a [u8], offset: usize) -> Option<Self> {
		if offset <= data.len() {
			Some(Stream { data, offset })
		} else {
			None
		}
	}

	/// Checks that stream reached the end of the data.
	#[inline]
	pub fn at_end(&self) -> bool {
		self.offset >= self.data.len()
	}

	/// Jumps to the end of the stream.
	///
	/// Useful to indicate that we parsed all the data.
	#[inline]
	pub fn jump_to_end(&mut self) {
		self.offset = self.data.len();
	}

	/// Returns the current offset.
	#[inline]
	pub fn offset(&self) -> usize {
		self.offset
	}

	/// Returns the trailing data.
	///
	/// Returns `None` when `Stream` is reached the end.
	#[inline]
	pub fn tail(&self) -> Option<&'a [u8]> {
		self.data.get(self.offset..)
	}

	/// Advances by `FromData::SIZE`.
	///
	/// Doesn't check bounds.
	#[inline]
	pub fn skip<T: FromData>(&mut self) {
		self.advance(T::SIZE);
	}

	/// Advances by the specified `len`.
	///
	/// Doesn't check bounds.
	#[inline]
	pub fn advance(&mut self, len: usize) {
		self.offset += len;
	}

	/// Advances by the specified `len` and checks for bounds.
	#[inline]
	pub fn advance_checked(&mut self, len: usize) -> Option<()> {
		if self.offset + len <= self.data.len() {
			self.advance(len);
			Some(())
		} else {
			None
		}
	}

	/// Parses the type from the steam.
	///
	/// Returns `None` when there is not enough data left in the stream
	/// or the type parsing failed.
	#[inline]
	pub fn read<T: FromData>(&mut self) -> Option<T> {
		self.read_bytes(T::SIZE).and_then(T::parse)
	}

	/// Parses the type from the steam at offset.
	#[inline]
	pub fn read_at<T: FromData>(data: &[u8], offset: usize) -> Option<T> {
		data.get(offset..offset + T::SIZE).and_then(T::parse)
	}

	/// Reads N bytes from the stream.
	#[inline]
	pub fn read_bytes(&mut self, len: usize) -> Option<&'a [u8]> {
		// An integer overflow here on 32bit systems is almost guarantee to be caused
		// by an incorrect parsing logic from the caller side.
		// Simply using `checked_add` here would silently swallow errors, which is not what we want.
		debug_assert!(self.offset as u64 + len as u64 <= u32::MAX as u64);

		let v = self.data.get(self.offset..self.offset + len)?;
		self.advance(len);
		Some(v)
	}

	/// Reads the next `count` types as a slice.
	#[inline]
	pub fn read_array16<T: FromData>(&mut self, count: u16) -> Option<LazyArray16<'a, T>> {
		let len = usize::from(count) * T::SIZE;
		self.read_bytes(len).map(LazyArray16::new)
	}

	// / Reads the next `count` types as a slice.
	// #[inline]
	// pub fn read_array32<T: FromData>(&mut self, count: u32) -> Option<LazyArray32<'a, T>> {
	// 	let len = usize::num_from(count) * T::SIZE;
	// 	self.read_bytes(len).map(LazyArray32::new)
	// }

	// #[allow(dead_code)]
	// #[inline]
	// pub fn read_at_offset16(&mut self, data: &'a [u8]) -> Option<&'a [u8]> {
	// 	let offset = self.read::<Offset16>()?.to_usize();
	// 	data.get(offset..)
	// }
}

fn parse_names(raw_face: &ttf_parser::RawFace) -> Option<(Vec<(String, Language)>, String, String, String)> {
	const NAME_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"name");
	let name_data = raw_face.table(NAME_TAG)?;
	let name_table = ttf_parser::name::Table::parse(name_data)?;

	let mut families = collect_families(ttf_parser::name_id::TYPOGRAPHIC_FAMILY, &name_table.names);
	// We have to fallback to Family Name when no Typographic Family Name was set.
	if families.is_empty() {
		families = collect_families(ttf_parser::name_id::FAMILY, &name_table.names);
	}
	// Make English US the first one.
	if families.len() > 1 {
		if let Some(index) = families.iter().position(|f| f.1 == Language::English_UnitedStates) {
			if index != 0 {
				families.swap(0, index);
			}
		}
	}

	if families.is_empty() {
		return None;
	}

	let post_script_name = name_table
		.names
		.into_iter()
		.find(|name| name.name_id == ttf_parser::name_id::POST_SCRIPT_NAME && name.is_supported_encoding())
		.and_then(|name| name_to_unicode(&name))?;

	let full_name = name_table
		.names
		.into_iter()
		.find(|name| name.name_id == ttf_parser::name_id::FULL_NAME && name.is_supported_encoding())
		.and_then(|name| name_to_unicode(&name))
		.unwrap_or_default();

	let unique_id = name_table
		.names
		.into_iter()
		.find(|name| name.name_id == ttf_parser::name_id::UNIQUE_ID && name.is_supported_encoding())
		.and_then(|name| name_to_unicode(&name))
		.unwrap_or_default();

	Some((families, post_script_name, unique_id, full_name))
}

fn collect_families(name_id: u16, names: &ttf_parser::name::Names) -> Vec<(String, Language)> {
	let mut families = Vec::new();
	for name in names.into_iter() {
		if name.name_id == name_id && name.is_unicode() {
			if let Some(family) = name_to_unicode(&name) {
				families.push((family, name.language()));
			}
		}
	}
	// If no Unicode English US family name was found then look for English MacRoman as well.
	if !families.iter().any(|f| f.1 == Language::English_UnitedStates) {
		for name in names.into_iter() {
			if name.name_id == name_id && name.is_mac_roman() {
				if let Some(family) = name_to_unicode(&name) {
					families.push((family, name.language()));
					break;
				}
			}
		}
	}
	families
}

fn name_to_unicode(name: &ttf_parser::name::Name) -> Option<String> {
	if name.is_unicode() {
		let mut raw_data: Vec<u16> = Vec::new();
		for c in ttf_parser::LazyArray16::<u16>::new(name.name) {
			raw_data.push(c);
		}
		String::from_utf16(&raw_data).ok()
	} else if name.is_mac_roman() {
		// We support only MacRoman encoding here, which should be enough in most cases.
		let mut raw_data = Vec::with_capacity(name.name.len());
		for b in name.name {
			raw_data.push(MAC_ROMAN[*b as usize]);
		}
		String::from_utf16(&raw_data).ok()
	} else {
		None
	}
}

fn parse_os2(raw_face: &ttf_parser::RawFace) -> (Style, Weight, Stretch) {
	const OS2_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"OS/2");
	let table = match raw_face.table(OS2_TAG).and_then(ttf_parser::os2::Table::parse) {
		Some(table) => table,
		None => return (Style::Normal, Weight::NORMAL, Stretch::NORMAL),
	};
	let style = match table.style() {
		ttf_parser::Style::Normal => Style::Normal,
		ttf_parser::Style::Italic => Style::Italic,
		ttf_parser::Style::Oblique => Style::Oblique,
	};
	let weight = table.weight();
	let stretch = table.width();
	(style, Weight(weight.to_number()), Stretch(stretch.to_number()))
}
fn parse_post(raw_face: &ttf_parser::RawFace) -> (bool, bool) {
	// We need just a single value from the `post` table, while ttf-parser will parse all.
	// Therefore we have a custom parser.
	const POST_TAG: ttf_parser::Tag = ttf_parser::Tag::from_bytes(b"post");
	let data = match raw_face.table(POST_TAG) {
		Some(v) => v,
		None => return (false, false),
	};
	// All we care about, it that u32 at offset 12 is non-zero.
	let monospaced = data.get(12..16) != Some(&[0, 0, 0, 0]);
	// Italic angle as f16.16.
	let italic = data.get(4..8) != Some(&[0, 0, 0, 0]);
	(monospaced, italic)
}

trait NameExt {
	fn is_mac_roman(&self) -> bool;
	fn is_supported_encoding(&self) -> bool;
}
impl NameExt for ttf_parser::name::Name<'_> {
	#[inline]
	fn is_mac_roman(&self) -> bool {
		use ttf_parser::PlatformId::Macintosh;
		// https://docs.microsoft.com/en-us/typography/opentype/spec/name#macintosh-encoding-ids-script-manager-codes
		const MACINTOSH_ROMAN_ENCODING_ID: u16 = 0;

		self.platform_id == Macintosh && self.encoding_id == MACINTOSH_ROMAN_ENCODING_ID
	}
	#[inline]
	fn is_supported_encoding(&self) -> bool {
		self.is_unicode() || self.is_mac_roman()
	}
}

/// Macintosh Roman to UTF-16 encoding table.
///
/// https://en.wikipedia.org/wiki/Mac_OS_Roman
#[rustfmt::skip]
const MAC_ROMAN: &[u16; 256] = &[
    0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007,
    0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F,
    0x0010, 0x2318, 0x21E7, 0x2325, 0x2303, 0x0015, 0x0016, 0x0017,
    0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F,
    0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
    0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,
    0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
    0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,
    0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
    0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,
    0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
    0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F,
    0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
    0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,
    0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
    0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F,
    0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1,
    0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8,
    0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3,
    0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC,
    0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF,
    0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8,
    0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211,
    0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8,
    0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB,
    0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153,
    0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA,
    0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02,
    0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1,
    0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4,
    0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC,
    0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7,
];

impl FontDB {
	pub fn query(&self, query: &Query) -> Option<&FaceInfo> {
		let candidates: Vec<_> = self
			.faces()
			.filter(|face| face.families.iter().any(|family| &family.0 == query.name))
			.collect();
		if !candidates.is_empty() {
			if let Some(index) = find_best_match(&candidates, query) {
				return Some(candidates[index]);
			}
		}
		None
	}
}
/// A database query.
///
/// Mainly used by `Database::query()`.
#[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Hash)]
pub struct Query<'a> {
	/// A prioritized list of font family names or generic family names.
	///
	/// [font-family](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#propdef-font-family) in CSS.
	pub name: &'a str,

	/// Specifies the weight of glyphs in the font, their degree of blackness or stroke thickness.
	///
	/// [font-weight](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-weight-prop) in CSS.
	pub weight: Weight,

	/// Selects a normal, condensed, or expanded face from a font family.
	///
	/// [font-stretch](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-stretch-prop) in CSS.
	pub stretch: Stretch,

	/// Allows italic or oblique faces to be selected.
	///
	/// [font-style](https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-style-prop) in CSS.
	pub style: Style,
}
impl<'a> Query<'a> {
	pub fn new(name: &'a str, weight: Weight, stretch: Stretch, style: Style) -> Self {
		Query {
			name,
			weight,
			stretch,
			style,
		}
	}
}

// https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#font-style-matching
// Based on https://github.com/servo/font-kit
#[inline(never)]
fn find_best_match(candidates: &[&FaceInfo], query: &Query) -> Option<usize> {
	debug_assert!(!candidates.is_empty());

	// Step 4.
	let mut matching_set: Vec<usize> = (0..candidates.len()).collect();

	// Step 4a (`font-stretch`).
	let matches = matching_set.iter().any(|&index| candidates[index].stretch == query.stretch);
	let matching_stretch = if matches {
		// Exact match.
		query.stretch
	} else if query.stretch <= Stretch::NORMAL {
		// Closest stretch, first checking narrower values and then wider values.
		let stretch = matching_set
			.iter()
			.filter(|&&index| candidates[index].stretch < query.stretch)
			.min_by_key(|&&index| query.stretch.0 - candidates[index].stretch.0);

		match stretch {
			Some(&matching_index) => candidates[matching_index].stretch,
			None => {
				let matching_index = *matching_set
					.iter()
					.min_by_key(|&&index| candidates[index].stretch.0 - query.stretch.0)?;

				candidates[matching_index].stretch
			}
		}
	} else {
		// Closest stretch, first checking wider values and then narrower values.
		let stretch = matching_set
			.iter()
			.filter(|&&index| candidates[index].stretch > query.stretch)
			.min_by_key(|&&index| candidates[index].stretch.0 - query.stretch.0);

		match stretch {
			Some(&matching_index) => candidates[matching_index].stretch,
			None => {
				let matching_index = *matching_set
					.iter()
					.min_by_key(|&&index| query.stretch.0 - candidates[index].stretch.0)?;

				candidates[matching_index].stretch
			}
		}
	};
	matching_set.retain(|&index| candidates[index].stretch == matching_stretch);

	// Step 4b (`font-style`).
	let style_preference = match query.style {
		Style::Italic => [Style::Italic, Style::Oblique, Style::Normal],
		Style::Oblique => [Style::Oblique, Style::Italic, Style::Normal],
		Style::Normal => [Style::Normal, Style::Oblique, Style::Italic],
	};
	let matching_style = *style_preference
		.iter()
		.find(|&query_style| matching_set.iter().any(|&index| candidates[index].style == *query_style))?;

	matching_set.retain(|&index| candidates[index].style == matching_style);

	// Step 4c (`font-weight`).
	//
	// The spec doesn't say what to do if the weight is between 400 and 500 exclusive, so we
	// just use 450 as the cutoff.
	let weight = query.weight.0;

	let matching_weight = if matching_set.iter().any(|&index| candidates[index].weight.0 == weight) {
		Weight(weight)
	} else if (400..450).contains(&weight) && matching_set.iter().any(|&index| candidates[index].weight.0 == 500) {
		// Check 500 first.
		Weight::MEDIUM
	} else if (450..=500).contains(&weight) && matching_set.iter().any(|&index| candidates[index].weight.0 == 400) {
		// Check 400 first.
		Weight::NORMAL
	} else if weight <= 500 {
		// Closest weight, first checking thinner values and then fatter ones.
		let idx = matching_set
			.iter()
			.filter(|&&index| candidates[index].weight.0 <= weight)
			.min_by_key(|&&index| weight - candidates[index].weight.0);

		match idx {
			Some(&matching_index) => candidates[matching_index].weight,
			None => {
				let matching_index = *matching_set.iter().min_by_key(|&&index| candidates[index].weight.0 - weight)?;
				candidates[matching_index].weight
			}
		}
	} else {
		// Closest weight, first checking fatter values and then thinner ones.
		let idx = matching_set
			.iter()
			.filter(|&&index| candidates[index].weight.0 >= weight)
			.min_by_key(|&&index| candidates[index].weight.0 - weight);

		match idx {
			Some(&matching_index) => candidates[matching_index].weight,
			None => {
				let matching_index = *matching_set.iter().min_by_key(|&&index| weight - candidates[index].weight.0)?;
				candidates[matching_index].weight
			}
		}
	};
	matching_set.retain(|&index| candidates[index].weight == matching_weight);

	// Ignore step 4d (`font-size`).

	// Return the result.
	matching_set.into_iter().next()
}

#[cfg(test)]
mod tests {
	use super::*;
	#[test]
	fn test_font_db() {
		let mut db = FontDB::default();
		db.load_system(false);
		for info in db.faces() {
			println!("=[{}]==[{}]=", info.full_name, info.unique_id);
			// if info.dlng.find("Hans").is_some() {
			// 	println!(
			// 		"{} - {} = {:?} -> {:?}.{} {}",
			// 		info.families.first().unwrap().0,
			// 		info.dlng,
			// 		info.weight,
			// 		info.source,
			// 		info.index,
			// 		info.slng,
			// 	);
			// }
		}
	}
}
